package com.fankui.crowd.service.impl;

import com.fankui.crowd.constant.CrowdConstant;
import com.fankui.crowd.entity.Admin;
import com.fankui.crowd.entity.AdminExample;
import com.fankui.crowd.exception.LoginAcctAlreadyInUserException;
import com.fankui.crowd.exception.LoginAcctAlreadyInUserForUpdateException;
import com.fankui.crowd.exception.LoginFailedException;
import com.fankui.crowd.mapper.AdminMapper;
import com.fankui.crowd.service.AdminService;
import com.fankui.crowd.util.CrowdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * ClassName AdminServiceImpl
 * Description TODO
 * Date 2023/7/27 17:33
 *
 * @Author 范奎
 * @Since JDK 11
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void saveAdmin(Admin admin) {
        // 1 密码加密
        admin.setUserPswd(passwordEncoder.encode(admin.getUserPswd()));
        // 2 生成当前系统时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        admin.setCreateTime(dateFormat.format(date));
        // 3 执行保存，如果登录账号被占用则抛出异常
        try {
            adminMapper.insert(admin);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUserException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
            // 如果当前捕获的不是DuplicateKeyException异常，则将异常继续向上抛出
            throw e;
        }
    }

    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    @Override
    public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
        // 1 根据登录账号查询Admin对象
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andLoginAcctEqualTo(loginAcct);
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        // 2 判断Admin对象是否为null
        if (adminList == null || adminList.size() == 0) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        if (adminList.size() > 1) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }
        // 3 如果Admin对象为null，则抛出异常
        Admin admin = adminList.get(0);
        if (admin == null) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        // 4 如果Admin对象不为null，则将数据库密码从Admin对象中取出
        String userPswdDB = admin.getUserPswd();
        // 5 将表单提交的明文密码进行加密
        String userPsedForm = CrowdUtil.md5(userPswd);
        // 6 对密码进行比较
        if (!Objects.equals(userPswdDB, userPsedForm)) {
            // 7 如果比较结果不一致，则抛出异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        // 8 如果一致，则返回Admin对象
        return admin;
    }

    @Override
    public PageInfo<Admin> getAdminPage(String keyword, Integer pageNum, Integer pageSize) {
        // 1 开启分页功能
        PageHelper.startPage(pageNum, pageSize);
        // 2 查询Admin数据
        List<Admin> adminList = adminMapper.selectAdminListByKeyword(keyword);
        // 3 将AdminList数据封装为PageInfo
        return new PageInfo<>(adminList);
    }

    @Override
    public void removeAdminById(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public Admin getAdminById(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public void updateAdmin(Admin admin) {
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUserForUpdateException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
            // 如果当前捕获的不是DuplicateKeyException异常，则将异常继续向上抛出
            throw e;
        }
    }

    @Override
    public Admin getAdminByLoginAcct(String username) {
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andLoginAcctEqualTo(username);
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        return adminList.get(0);
    }
}
